<template>
<view class="container">
  <!-- 头部区域已去除，搜索框紧贴tab栏 -->
  <view class="search-area">
    <view class="search-box">
      <uni-icons class="search-icon" type="search" size="18" color="#bcbcbc" />
      <input class="search-input" v-model="searchText" placeholder="搜索联系人或分组" @input="handleSearch" @confirm="handleSearch" />
    </view>
  </view>
  <!-- 分组列表 -->
  <scroll-view class="group-list" scroll-y>
    <!-- 空状态 -->
    <view v-if="!groupList.length" class="empty-container">
      <text>暂无分组</text>
    </view>
    <!-- 原有分组渲染逻辑 -->
    <template v-else v-for="group in filteredGroupList" :key="group.id">
      <view
        class="group-card"
        :style="{ marginLeft: '0rpx' }"
      >
        <view class="group-header" :style="{ borderLeftColor: group.color }" @click="toggleGroup(group)">
          <view class="group-info">
            <view class="expand-icon">
              <uni-icons :type="group.expanded ? 'bottom' : 'right'" size="16" color="#666666" />
            </view>
            <view class="group-name">{{ group.name }}</view>
            <view class="group-count">{{ group.count || group.members.length }}人</view>
          </view>
          <!-- 分组卡片部分，去除加号按钮，只保留编辑 -->
          <view class="group-actions" @click.stop>
            <uni-icons @click="handleAddContactToGroup(group, $event)" class="action-icon" type="plusempty" size="20" color="#666666" title="添加联系人" />
            <uni-icons @click="handleEditGroup(group, $event)" class="action-icon" type="compose" size="20" color="#666666" />
            <uni-icons @click="handleDeleteGroup(group, $event)" class="action-icon" type="trash" size="20" color="#ff4757" title="删除分组" />
          </view>
        </view>
        <view v-if="group.expanded" class="member-list">
          <view
            v-for="member in group.members"
            :key="member.id"
            class="member-item"
          >
            <view class="member-info" @click="navigateToContactDetail(member)">
              <view class="member-avatar">
                <image v-if="member.avatar" class="avatar-image" :src="member.avatar" mode="aspectFill" />
                <uni-icons v-else type="person-filled" size="24" color="#CCCCCC" />
              </view>
              <view class="member-name">{{ member.name }}</view>
              <view v-if="member.phone" class="member-phone">{{ member.phone }}</view>
            </view>
            <view class="member-actions">
              <view @tap.stop="handleDeleteMember(group, member)" class="delete-btn">
                <uni-icons type="trash" size="18" color="#ff4757" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </template>
  </scroll-view>
  
  <!-- 分组编辑弹窗 -->
  <view v-if="showPopup" class="popup-mask" @click="closePopup">
    <view class="popup-container" @click.stop>
      <view class="popup-content">
        <view class="popup-title">{{ editingGroup ? '编辑分组' : '新建分组' }}</view>
        <view class="form-item">
          <input class="input" v-model="groupForm.name" placeholder="分组名称" />
        </view>
        <view class="color-picker">
          <view v-for="color in colors" :key="color" class="color-item"
            :class="{ active: groupForm.color === color }"
            :style="{ backgroundColor: color }"
            @click="groupForm.color = color">
          </view>
        </view>
        <view class="popup-buttons">
          <view class="cancel-btn" @tap="closePopup">取消</view>
          <view class="confirm-btn" @tap="saveGroup">确定</view>
        </view>
      </view>
    </view>
  </view>

  <!-- 联系人选择弹窗 -->
  <s-contact-selector
    :visible="showContactSelector"
    title="选择联系人"
    :multiple="true"
    v-model="selectedContacts"
    @update:visible="showContactSelector = $event"
    @confirm="handleContactSelected"
    @cancel="handleContactCancel"
  />
  <!-- 悬浮添加按钮 -->
  <view class="floating-btn" @tap="handleAddGroup">
    <text class="btn-icon">+</text>
  </view>
</view>
</template>

<script>
import { ref, reactive, nextTick, onMounted, computed } from 'vue';
import GroupApi from '@/sheep/api/group/group.js';
import SContactSelector from '@/sheep/components/s-contact-selector/s-contact-selector.vue';

export default {
  name: 'GroupTab',
  components: {
    SContactSelector
  },
  setup() {
    const showSearch = ref(false);
    const searchText = ref('');
    const groupPopup = ref();
    const editingGroup = ref(null);
    const showPopup = ref(false); // 控制分组编辑弹窗显示
    
    // 联系人选择相关状态
    const showContactSelector = ref(false);
    const selectedContacts = ref([]);
    const currentGroup = ref(null); // 当前要添加联系人的分组
    
    const colors = [
      '#4080FF',
      '#36B374',
      '#F6BD16',
      '#F6666E',
      '#6657FF',
      '#6DC8EC',
      '#9270CA',
      '#FF9A2E'
    ];
    
    const groupForm = reactive({
      name: '',
      color: colors[0]
    });
    
    const groupList = ref([]);
    const allContacts = ref([]); // 存储所有联系人数据，用于搜索

    // 计算过滤后的分组列表
    const filteredGroupList = computed(() => {
      if (!searchText.value.trim()) {
        return groupList.value;
      }

      const keyword = searchText.value.toLowerCase().trim();
      return groupList.value.map(group => {
        // 检查分组名是否匹配
        const groupMatches = group.name.toLowerCase().includes(keyword);
        
        // 检查分组中的联系人是否匹配
        const matchedMembers = group.members.filter(member => 
          member.name.toLowerCase().includes(keyword) ||
          (member.phone && member.phone.includes(keyword)) ||
          (member.nickname && member.nickname.toLowerCase().includes(keyword))
        );

        // 如果分组名匹配或有联系人匹配，则显示该分组
        if (groupMatches || matchedMembers.length > 0) {
          return {
            ...group,
            members: groupMatches ? group.members : matchedMembers, // 如果分组名匹配显示所有成员，否则只显示匹配的成员
            expanded: true // 有搜索结果的分组自动展开
          };
        }
        
        return null;
      }).filter(Boolean); // 过滤掉null值
    });

    const handleSearchClick = () => {
      showSearch.value = !showSearch.value;
      if (!showSearch.value) {
        // 关闭搜索时清空搜索内容
        searchText.value = '';
      }
    };

    // 处理搜索
    const handleSearch = () => {
      // 搜索逻辑由computed属性filteredGroupList自动处理
      // 这里可以添加其他搜索相关的逻辑，如搜索统计等
    };

    // 只在点击加号/编辑按钮时弹窗
    const handleAddGroup = () => {
      editingGroup.value = null;
      groupForm.name = '';
      groupForm.color = colors[0];
      showPopup.value = true;
    };

    const toggleGroup = (group) => {
      group.expanded = !group.expanded;
    };

    const handleEditGroup = (group, event) => {
      event && event.stopPropagation && event.stopPropagation();
      editingGroup.value = group;
      groupForm.name = group.name;
      groupForm.color = group.color;
      showPopup.value = true;
    };

    const handleAddContactToGroup = (group, event) => {
      event && event.stopPropagation && event.stopPropagation();
      currentGroup.value = group;
      selectedContacts.value = [];
      showContactSelector.value = true;
    };

    // 处理联系人选择确认
    const handleContactSelected = async (contacts) => {
      if (!currentGroup.value || !contacts || contacts.length === 0) {
        return;
      }

      // 过滤掉已经存在的联系人
      const existingContactIds = currentGroup.value.members.map(member => member.id);
      const newContacts = contacts.filter(contact => !existingContactIds.includes(contact.id));

      if (newContacts.length === 0) {
        uni.showToast({
          title: '所选联系人已在该分组中',
          icon: 'none'
        });
        return;
      }

      try {
        // 调用批量添加联系人接口
        const contactIds = newContacts.map(contact => contact.id);
        const res = await GroupApi.batchAddGroupContacts({
          groupId: currentGroup.value.id,
          contactIds: contactIds
        });

        // 检查接口返回是否成功 (code 为 0 表示成功)
        if (res.code !== 0) {
          uni.showToast({
            title: res.msg || '添加联系人失败',
            icon: 'none'
          });
          return;
        }

        // 接口调用成功后，更新本地数据
        newContacts.forEach(contact => {
          currentGroup.value.members.push({
            id: contact.id,
            name: contact.name,
            avatar: contact.avatar,
            phone: contact.phone
          });
        });

        // 更新分组数量
        currentGroup.value.count = currentGroup.value.members.length;

        uni.showToast({
          title: `成功添加 ${newContacts.length} 个联系人`,
          icon: 'success'
        });

        // 清理状态
        currentGroup.value = null;
        selectedContacts.value = [];
        showContactSelector.value = false;

      } catch (error) {
        console.error('添加联系人到分组失败:', error);
        uni.showToast({
          title: '添加联系人失败',
          icon: 'none'
        });
      }
    };

    // 处理联系人选择取消
    const handleContactCancel = () => {
      currentGroup.value = null;
      selectedContacts.value = [];
      showContactSelector.value = false;
    };

    const closePopup = () => {
      showPopup.value = false;
    };

    const saveGroup = async () => {
      if (!groupForm.name) {
        uni.showToast({
          title: '请输入分组名称',
          icon: 'none'
        });
        return;
      }
      
      try {
        const params = {
          groupId: editingGroup.value ? editingGroup.value.id : null,
          groupName: groupForm.name,
          color: groupForm.color,
        };
        
        const res = await GroupApi.addOrUpdateContactGroup(params);
        
        // 检查接口返回是否成功 (code 为 0 表示成功)
        if (res.code !== 0) {
          uni.showToast({
            title: res.msg || '操作失败',
            icon: 'none'
          });
          return;
        }
        
        if (editingGroup.value) {
          // 本地更新
          const group = groupList.value.find(g => g.id === editingGroup.value.id);
          if (group) {
            group.name = groupForm.name;
            group.color = groupForm.color;
          }
        } else {
          // 本地新增 - 使用接口返回的ID
          groupList.value.push({
            id: res.data || Date.now(), // 优先使用接口返回的分组ID
            name: groupForm.name,
            color: groupForm.color,
            count: 0,
            members: [],
            expanded: false
          });
        }
        
        closePopup();
        uni.showToast({
          title: editingGroup.value ? '编辑成功' : '创建成功',
          icon: 'success'
        });
      } catch (e) {
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    };

    // 查询分组列表
    const fetchGroupList = async () => {
      try {
        const res = await GroupApi.queryGroupList({});
        if (res.code === 0 && res.data) {
          groupList.value = res.data.map(group => ({
            id: group.groupId,
            name: group.groupName,
            color: group.color || colors[Math.floor(Math.random() * colors.length)],
            count: group.groupContactCount,
            members: [],
            expanded: false
          }));
          
          // 异步查询每个分组的联系人数据
          fetchAllGroupContacts();
        }
      } catch (error) {
        console.error('获取分组列表失败:', error);
        uni.showToast({
          title: '获取分组列表失败',
          icon: 'none'
        });
      }
    };

    // 异步查询所有分组的联系人数据
    const fetchAllGroupContacts = async () => {
      const contactPromises = groupList.value.map(async (group) => {
        try {
          const res = await GroupApi.queryContactByGroup({ groupId: group.id });
          if (res.code === 0 && res.data) {
            const contacts = res.data.map(contact => ({
              id: contact.id,
              name: contact.name,
              nickname: contact.nickname,
              phone: contact.phoneNumber,
              avatar: contact.avatarUrl,
              email: contact.email,
              companyName: contact.companyName,
              homeAddress: contact.homeAddress,
              workAddress: contact.workAddress,
              work: contact.work,
              remark: contact.remark,
              school: contact.school,
              groupId: group.id,
              groupName: group.name
            }));
            
            // 更新分组的联系人数据
            group.members = contacts;
            group.count = contacts.length;
            
            // 添加到全局联系人列表用于搜索
            allContacts.value.push(...contacts);
          }
        } catch (error) {
          console.error(`获取分组${group.name}的联系人失败:`, error);
        }
      });

      // 等待所有分组联系人数据加载完成
      await Promise.allSettled(contactPromises);
    };

    // 组件挂载时获取数据
    onMounted(() => {
      fetchGroupList();
    });

    // methods内新增
    const navigateToContactDetail = (member) => {
      if (member && member.id) {
        uni.navigateTo({
          url: `/pages/contact/detail?id=${member.id}`
        });
      }
    };

    // 删除群组成员
    const handleDeleteMember = (group, member) => {
      console.log('handleDeleteMember 被调用', { group, member });
      uni.showToast({ title: '点击了删除按钮', icon: 'none' });
      uni.showModal({
        title: '确认删除',
        content: `确定要将"${member.name}"从该分组中移除吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' });
              const response = await GroupApi.batchDelGroupContacts({
                groupId: group.id,
                contactIds: [member.id]
              });
              
              if (response.code === 0) {
                // 从本地数据中移除
                group.members = group.members.filter(m => m.id !== member.id);
                group.count = group.members.length;
                
                uni.showToast({ title: '移除成功', icon: 'success' });
              } else {
                uni.showToast({ title: response.msg || '移除失败', icon: 'none' });
              }
            } catch (error) {
              console.error('从分组移除联系人失败:', error);
              uni.showToast({ title: '移除失败', icon: 'none' });
            } finally {
              uni.hideLoading();
            }
          }
        }
      });
    };

    // 在setup中添加handleDeleteGroup方法
    const handleDeleteGroup = (group, event) => {
      event && event.stopPropagation && event.stopPropagation();
      uni.showModal({
        title: '确认删除',
        content: `确定要删除分组“${group.name}”吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' });
              const response = await GroupApi.delContactGroup({ groupId: group.id });
              if (response.code === 0) {
                groupList.value = groupList.value.filter(g => g.id !== group.id);
                uni.showToast({ title: '删除成功', icon: 'success' });
              } else {
                uni.showToast({ title: response.msg || '删除失败', icon: 'none' });
              }
            } catch (error) {
              uni.showToast({ title: '删除失败', icon: 'none' });
            } finally {
              uni.hideLoading();
            }
          }
        }
      });
    };

    return {
      showSearch,
      searchText,
      groupPopup,
      editingGroup,
      showPopup,
      showContactSelector,
      selectedContacts,
      currentGroup,
      colors,
      groupForm,
      groupList,
      allContacts,
      filteredGroupList,
      handleSearchClick,
      handleSearch,
      handleAddGroup,
      toggleGroup,
      handleEditGroup,
      handleAddContactToGroup,
      handleContactSelected,
      handleContactCancel,
      closePopup,
      saveGroup,
      fetchGroupList,
      fetchAllGroupContacts,
      navigateToContactDetail,
      handleDeleteMember,
      handleDeleteGroup
    };
  }
};
</script>

<style scoped>
page {
  height: 100%;
}
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #F8F8F8;
}
.header {
  padding: 30rpx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #FFFFFF;
}
.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
}
.header-actions {
  display: flex;
  align-items: center;
}
.action-icon {
  margin-left: 30rpx;
  width: 22px;
  height: 22px;
}
.search-area {
  padding: 0;
  margin-top: 0;
  margin-bottom: 12rpx;
  background: #fff;
}
.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 0 16rpx;
  height: 40px;
  border-radius: 20px;
  margin: 0 16rpx;
}
.search-icon {
  width: 18px;
  height: 18px;
  margin-right: 8px;
  color: #bcbcbc;
}
.search-input {
  flex: 1;
  font-size: 15px;
  background: transparent;
  border: none;
  outline: none;
  color: #333;
  height: 40px;
  line-height: 40px;
}
::v-deep .search-input::placeholder {
  color: #bcbcbc;
  font-size: 15px;
}
.filter-tags {
  display: flex;
  margin-top: 20rpx;
}
.tag {
  padding: 10rpx 20rpx;
  margin-right: 20rpx;
  border-radius: 4rpx;
  font-size: 12px;
  color: #666666;
  background-color: #F5F5F5;
}
.tag.active {
  color: #FFFFFF;
  background-color: #4080FF;
}
.group-list {
  flex: 1;
  overflow: auto;
  padding: 0;
}
.group-card {
  background-color: #FFFFFF;
  border-radius: 0;
  margin-bottom: 20rpx;
  overflow: hidden;
}
.expand-icon {
  padding: 10rpx;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
}
.group-info {
  display: flex;
  align-items: center;
}
.group-header {
  padding: 30rpx 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 8rpx solid #4080FF;
}
.group-info {
  display: flex;
  align-items: center;
}
.group-name {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  margin-right: 20rpx;
}
.group-count {
  font-size: 12px;
  color: #999999;
}
.group-actions {
  display: flex;
  align-items: center;
}
.member-list {
  padding: 0;
}
.member-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0 20rpx 20rpx;
  border-top: 1px solid #F5F5F5;
}
.member-info {
  display: flex;
  align-items: center;
  flex: 1;
}
.member-avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 24rpx;
  background-color: #F5F5F5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 24rpx;
}
.member-name {
  font-size: 14px;
  color: #333333;
}
.member-phone {
  font-size: 12px;
  color: #999999;
  margin-left: 20rpx;
}
.member-actions {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  margin-right: 16rpx;
}
.delete-btn {
  margin-right: 16rpx;
}
.drag-handle {
  width: 20px;
  height: 20px;
}
.toolbar {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  background-color: #FFFFFF;
  border-top: 1px solid #EEEEEE;
}
.tool-btn {
  flex: 1;
  margin: 0 10rpx;
}
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.popup-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.popup-content {
  width: 600rpx;
  background-color: #FFFFFF;
  border-radius: 12rpx;
  padding: 40rpx;
  max-height: 80vh;
  overflow-y: auto;
}
.popup-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  margin-bottom: 40rpx;
}
.form-item {
  margin-bottom: 30rpx;
}
.input {
  height: 80rpx;
  border: 1px solid #EEEEEE;
  border-radius: 8rpx;
  padding: 0rpx 16rpx;
  font-size: 14px;
}
.color-picker {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 40rpx;
}
.color-item {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin: 10rpx;
  cursor: pointer;
}
.color-item.active {
  border: 4rpx solid #FFFFFF;
  box-shadow: 0 0 0 2rpx #4080FF;
}
.popup-buttons {
  display: flex;
  justify-content: space-between;
}
.cancel-btn, .confirm-btn {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 15px;
  font-weight: 400;
  border-radius: 8rpx;
  margin: 0 4rpx;
  box-sizing: border-box;
  user-select: none;
}
.cancel-btn {
  background-color: #f0f2f5;
  color: #666;
}
.confirm-btn {
  background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
  color: #fff;
  box-shadow: 0 2rpx 6rpx rgba(43, 127, 243, 0.18);
}
.cancel-btn:active, .confirm-btn:active {
  opacity: 0.8;
}
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #8e8e93;
  font-size: 14px;
}
.add-btn {
  margin-top: 20px;
  background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
  color: #fff;
  font-size: 14px;
  padding: 6px 20px;
  border-radius: 20px;
  border: none;
  box-shadow: 0 4px 12px rgba(43, 127, 243, 0.25);
  transition: all 0.3s ease;
}
.add-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(43, 127, 243, 0.4);
}
.floating-btn {
  position: fixed;
  right: 30rpx;
  bottom: 160rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(43, 127, 243, 0.35);
  z-index: 100;
  transition: all 0.3s ease;
}
.btn-icon {
  color: #fff;
  font-size: 50rpx;
  font-weight: 300;
  text-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.floating-btn:active {
  transform: scale(0.9);
  box-shadow: 0 4rpx 16rpx rgba(43, 127, 243, 0.5);
}
</style> 